package com.alibaba.basic.util;

import com.alibaba.basic.jwt.JwtUtils;
import com.alibaba.basic.jwt.Payload;
import com.alibaba.basic.jwt.RsaUtils;
import com.alibaba.basic.jwt.UserInfo;
import com.alibaba.user.domain.Logininfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

/**
 * 获取登录信息的上下文：把登录的相关信息放到这里面，方便调用
 */
@Slf4j
public class LoginContext {
    /**
     * @param request
     * @return 如果是后台需要返回employee，如果是前台返回user
     */
    public static Logininfo getLoginUser(HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            if (StringUtils.isEmpty(token)){
                return null;
            }
            //获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(JwtRasHolder.INSTANCE.getJwtRsaPubData());
            //获取载荷 = 数据
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);


            UserInfo userInfo = payload.getUserInfo();
            if (userInfo==null){
                log.error("payloadData is null!");
                return null;
            }
            return userInfo.getLogininfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}